package com.phoenix.shuaidatabase.utils;

import java.util.Arrays;
import java.util.List;

public class PrintThreadUsingSynchronized implements Runnable{

    static final int n = 100;
    static int cur = 0;
    int k;
    final Object pre;
    final Object self;

    public PrintThreadUsingSynchronized(int k, Object pre, Object self) {
        this.k = k;
        this.pre = pre;
        this.self = self;
    }

    @Override
    public void run() {
        while(cur <= n) {
            synchronized (pre) {
                synchronized (self) {
                    System.out.println("线程" + k + ": " + cur);
                    cur++;
                    self.notify();
                }
                try {
                    System.out.println("线程" + k + "wait here");
                    pre.wait();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        synchronized (self) {
            self.notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object zero = new Object();
        Object one = new Object();
        Object two = new Object();
        Object three = new Object();
        Object four = new Object();
        PrintThreadUsingSynchronized pzero  = new PrintThreadUsingSynchronized(0, four, zero);
        PrintThreadUsingSynchronized pone = new PrintThreadUsingSynchronized(1, zero, one);
        PrintThreadUsingSynchronized ptwo = new PrintThreadUsingSynchronized(2, one, two);
        PrintThreadUsingSynchronized pthree = new PrintThreadUsingSynchronized(3, two, three);
        PrintThreadUsingSynchronized pfour = new PrintThreadUsingSynchronized(4, three, four);
        List<PrintThreadUsingSynchronized> printThreadUsingSynchronizeds = Arrays.asList(pzero, pone, ptwo, pthree, pfour);
        for(int i = 0;i<5;i++) {
            new Thread(printThreadUsingSynchronizeds.get(i)).start();
            Thread.sleep(10);
        }
    }

}
